package com.sponge.controller;


import com.sponge.result.ApiError;
import com.sponge.result.ServiceResult;
import com.sponge.result.SpongeException;
import com.sponge.service.CreditEntityService;
import com.sponge.utils.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.BigInteger;

@RestController
public class ContractController {

    private String username = "Guanhao";
    private String password = "12345678";
    private String verifyCode = "123456";

    @Autowired
    private CreditEntityService creditEntityService;


    @RequestMapping(value = "/user_login", method = RequestMethod.GET)
    public ServiceResult<String> login(@RequestParam String username, @RequestParam String password, @RequestParam String verifyCode) throws SpongeException {
        LogUtil.info(ContractController.class, "username==" + username + "password==" + password + "verifyCode==" + verifyCode);
        if (password.equals(this.password)) {
            if (verifyCode.equals(this.verifyCode)) {
                String account = creditEntityService.createAccount(username, password);
                return new ServiceResult<>(account);
            } else {
                throw new SpongeException(ApiError.VERIFY_CODE_ERROR);
            }
        } else {
            throw new SpongeException(ApiError.WRONG_PASSWORD);
        }
    }

    @RequestMapping(value = "/query_balance", method = RequestMethod.GET)
    public ServiceResult<String> queryBalance(@RequestParam String address) throws SpongeException {
        BigDecimal balance = creditEntityService.getBalance(address);
        return new ServiceResult<>(balance.toString());
    }

    @RequestMapping(value = "/buy_token", method = RequestMethod.GET)
    public ServiceResult<String> buyToken(@RequestParam String address, @RequestParam String count) throws SpongeException {
        try {
            boolean transferStatus = creditEntityService.transferToken(address,count);
            return ServiceResult.getResult(transferStatus);
        } catch (SpongeException e) {
            e.printStackTrace();
        }
        throw new SpongeException(ApiError.UNKNOWN_ERROR);

    }

    @RequestMapping(value = "/query_token",method = RequestMethod.GET)
    public ServiceResult<String> queryToken(@RequestParam String address) throws SpongeException {
        try {
            BigInteger balance = creditEntityService.queryToken(address);
            return new ServiceResult<>(balance.toString());
        } catch (SpongeException e) {
            e.printStackTrace();
        }
        throw new SpongeException(ApiError.UNKNOWN_ERROR);
    }


}
